<?php
require_once 'response.php';
require_once 'connect_config.php';
require('../config.php');

/*---------------------变量参数定义-------------------------------*/
$courseid=$_GET['courseid'];
$token = $_GET['token'];
if(!$token)
{
	$username = $_POST['username'];	
	$courseid = $_POST['courseid'];
}

$status = false;
$msg = '';
$data = array();

//数据库连接
$conn = mysqli_connect(DB_HOST,DB_USER,DB_PWD,DB_NAME,DB_PORT) or die('数据库连接失败');

//查询学生ID
if($token)
{
	$query = "select * from mdl_token where token = '$token'";
	$data1 = mysqli_query($conn, $query);         
	$row = mysqli_fetch_array($data1);
	$userid;
	if($row){
		$userid= $row['user_id'];
	}else{
		$msg =	mysqli_errno($conn);
	}
}
else if($username)
{
	$query2 = "select * from mdl_user where username = '$username'";
	$data2 = mysqli_query($conn, $query2);         
	$row2 = mysqli_fetch_array($data2);
	if($row2){
		$userid= $row2['id'];
	}else{
		$msg =	mysqli_errno($conn);
	}
}

if($userid){
    $enrolids=array();
    $query2 = "select * from mdl_user_enrolments where userid = '$userid'";
    $data2=mysqli_query($conn, $query2);
    $i=0;
    while($row2 = mysqli_fetch_array($data2)){
        $enrolids[$i]['enrolid']=$row2['enrolid'];
        $i++;
    } 

    $query3 = "select * from mdl_enrol where courseid='$courseid'";
    $data3=mysqli_query($conn, $query3);
    $j=0;
    $size=sizeof($enrolids);
    $flag=true;
    while($row3 = mysqli_fetch_array($data3)){
        while($j<$size){
            if($enrolids[$j]['enrolid']==$row3['id']){
                $status=true;
                $msg="success";
                echo Response::json($status,$msg,$data);
                $flag=false;
                break;
            }
            $j++;
        }
        $j=0;
    }
    if($flag){
        $status=false;
        $msg="The course is not selected!";
        echo Response::json($status,$msg,$data);
    }
}else{
	$status = false;
	$msg = "login fail!";
	echo Response::json($status,$msg,$data);
}
?>
